﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Indicator.cs" company="">
//   
// </copyright>
// <summary>
//   The indicator.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;

namespace Systemathics.FrameWork
{
    public class Indicator : TimeSeries, IDisposable
    {
        public Guid Id { get; private set; }
        public event EventHandler<Indicator> OnIndicator;

        private Bars Bars;
        protected Data DataType;
        protected Instrument Instrument;
        protected TimeSeries TimeSeries;

        protected Indicator(Instrument instr, Data dt,BarType? barType,int value)
        {
            if (instr != null)
            {
                Instrument = instr;
                Id = instr.Id;
                DataType = dt;
                
                switch (DataType)
                {
                    case Data.Trade:
                        Instrument.OnTrade += BuildIndicatorOnNewTrade;
                        break;
                    case Data.Quote:
                        Instrument.OnBlotter += BuildIndicatorOnNewQuote;
                        break;
                    case Data.Bar: 
                        Bars = new Bars(Instrument, (BarType)barType, value);
                        Bars.OnBar += OnBar;
                        break;
                    default:
                        break;
                }
            }
        }

        private void OnBar(object sender, Bar e)
        {
            // (!(Decimal.IsNaN(e.Open) || double.IsNaN(e.Weighted)))
                Calculate(e);
        }
        private void BuildIndicatorOnNewTrade(object sender, Trade e)
        {
            Calculate(e.Clone() as Trade);
        }
        private void BuildIndicatorOnNewQuote(object sender, Blotter e)
        {
            Calculate(e[QuoteLevel.One].Clone() as Quote);
        }

        protected virtual void Calculate(object price)
        {
        }
        protected void IndicatorCalculated(Indicator e)
        {
            if (OnIndicator != null)
                OnIndicator(this, e);
        }

        public void Dispose()
        {
            Bars.OnBar -= OnBar;
        }
    }
}